package dbs

import (
	"bytes"
	"fmt"
	"os/exec"
)

var PHP_PATH = "/usr/local/opt/php@8.0.3/bin/php"
var ARTISAN_PATH = "/Users/cpp/project/ndcube_back/artisan"
var LOG_PATH = "../error.log"

// 设备告警表结构体
type Event struct {
	FEventId   int    `db:"FEventId"`
	FLastTime  int    `db:"FLastTime"`
	FunInstId  string `db:"FunInstId"`
	DevInstId  string `db:"DevInstId"`
	FFirstTime int    `db:"FFirstTime"`
	FStatus    int    `db:"FStatus"`
	FEvtType   string `db:"FEvtType"`
	FMsgId     int    `db:"FMsgId"`
	FMsg       string `db:"FMsg"`
	FNum       int    `db:"FNum"`
}

func SyncMonitorAlarm() {
	lastFEventId := getLastFEventId()
	events := getMonitorEvent(lastFEventId)
	insertMonitorAlarmLog(events)
}

func getLastFEventId() int {
	db := MysqlDbMap["default"]
	var num int
	err := db.QueryRow("SELECT max(`FEventId`) FROM `monitor_alarm_logs`").Scan(&num)
	if err != nil {
		return 0
	}
	return num
}

func getMonitorEvent(lastFEventId int) []Event {
	db := MysqlDbMap["monitor"]
	events := make([]Event, 0)
	rows, err := db.Query("SELECT FEventId, FLastTime, FunInstId, DevInstId, FFirstTime,  FStatus, FEvtType, FMsgId, FMsg, FNum FROM `funeventlog` WHERE FEventId > ?", lastFEventId)

	if err != nil {
		fmt.Println(err)
	} else {
		for rows.Next() {
			var e Event
			rows.Scan(&e.FEventId, &e.FLastTime, &e.FunInstId, &e.DevInstId, &e.FFirstTime, &e.FStatus, &e.FEvtType, &e.FMsgId, &e.FMsg, &e.FNum)
			events = append(events, e)
		}
	}

	return events
}

func insertMonitorAlarmLog(events []Event) {
	db := MysqlDbMap["default"]
	for _, e := range events {
		ret, err := db.Exec("INSERT INTO monitor_alarm_logs values(?,?,?,?,?,?,?,?,?,?)",
			e.FEventId, e.FLastTime, e.FunInstId, e.DevInstId, e.FFirstTime, e.FStatus, e.FEvtType, e.FMsgId, e.FMsg, e.FNum)

		if err != nil {
			fmt.Println(err)
			return
		}

		execCommand(e.FEventId)

		lastInsertID, _ := ret.LastInsertId()
		fmt.Println("LastInsertID:", lastInsertID)
	}
}

func execCommand(id int) {
	cmd := exec.Command(PHP_PATH, ARTISAN_PATH, "ops:create_or_close_monitor_workorder", fmt.Sprintf("%d", id))
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err != nil {
		fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
		return
	}
	fmt.Println("Result: " + out.String())
}
